package com.archstoday.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.archstoday.R;
import com.archstoday.adapter.SendArticleAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.UserInfoEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.CropUtil;
import com.base.utils.ImageUtil;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.gifdialog.DialogUtil;
import com.gifdialog.GifDialog;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写文章页面
 */
public class SendArticleActivity extends AsScrollBaseActivity {

    private TextView mTitleTv;
    private EditText mTitleEdit, mContentEdit;
    private GridView mImgsView;

    private SendArticleAdapter mAdapter;
    private String mTitleStr, mContentStr;

    private List<Bitmap> mImgs;
    private GifDialog loadingDialog;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_send_article);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mTitleEdit = (EditText) findViewById(R.id.send_title_edit);
        mContentEdit = (EditText) findViewById(R.id.send_content_edit);
        mImgsView = (GridView) findViewById(R.id.send_img_view);
    }

    @Override
    protected void initData(Bundle bundle) {
        mTitleTv.setText(R.string.user_write_article);
        mImgs = new ArrayList<>();

        if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))){
            showToast(R.string.user_userid_null);
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            appFinish();
        }

        mAdapter = new SendArticleAdapter(mContext, click);
        mImgsView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.cancel_btn);
        setOnClickListener(R.id.send_btn);

        mImgsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mAdapter.getCount() >= 1 && i < (mAdapter.getCount() - 1)) {

                } else {
                    showMoreImgTypeDialog();
                }
            }
        });
    }

    @Override
    public void treatClickEvent(View view) {
        switch (view.getId()) {
            case R.id.cancel_btn:
                appFinish();
                break;
            case R.id.send_btn:
                mTitleStr = mTitleEdit.getText().toString();
                mContentStr = mContentEdit.getText().toString();
                if (StringUtil.isEmpty(mTitleStr)) {
                    showToast(R.string.send_article_title);
                } else if (StringUtil.isEmpty(mContentStr)) {
                    showToast(R.string.send_article_content);
                } else {
                    loadingDialog = new DialogUtil().showGifdialog(mContext);

                    if (!loadingDialog.isShowing()) {
                        sendArticle();
                    }
                    loadingDialog.show();
                }
                break;
            case R.id.item_del_btn:
                int position = (int) view.getTag();
                mImgs.remove(mAdapter.getItem(position));
                mAdapter.removeData(mAdapter.getItem(position));
                break;
        }
    }

    private String getImgs() {
        try {
            List<Map<String, String>> imgs = new ArrayList<>();
            for (int i = 0; i < mImgs.size(); i++) {
                Map<String, String> map = new HashMap<>();
                    map.put("img",
                            URLEncoder.encode("data:image/jpeg;base64,"
                                    + ToolUtils.bitmaptoString(
                                    ToolUtils.compressImage(mImgs.get(i))), "UTF-8"));

                imgs.add(map);
            }

            JSONArray jsonArray = new JSONArray(imgs);

            return jsonArray.toString();
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    private void sendArticle() {
        initParameter();
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("name", getIntent().getStringExtra("nick"));
        mParams.put("title", mTitleStr);
        mParams.put("content", mContentStr );
        mParams.put("imgs", getImgs());
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("plat", "android");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SEND_ADD_ARTICLE),
                AsRes.SEND_ADD_ARTICLE, mParams, BaseEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.SEND_ADD_ARTICLE) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }

            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                appFinish();
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_GALLERY:
                if (resultCode == RESULT_OK) {
////                    cropPhoto(data.getData());
//                    cropImageUri = Uri.fromFile(fileCropUri);
//                    Uri newUri = Uri.parse(CropUtil.getPath(this, data.getData()));
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        newUri = FileProvider.getUriForFile(this, "com.base.provider", new File(newUri.getPath()));
//                    }
////                    cropImageUri(newUri, cropImageUri);
//                    ContentResolver cr = this.getContentResolver();
//                    Bitmap bmp = null;
//                    try {
//                        bmp = MediaStore.Images.Media.getBitmap(cr, newUri);
//                    } catch (IOException e) {
//
//                    }
//                    if (bmp != null) {
//                        mAdapter.addData(bmp);
//                        mImgs.add(ToolUtils.ratio(bmp, 240f, 120f));
//                    }
//                    List<String> pathList = Album.parseResult(data);
//                    for (int i = 0; i < pathList.size(); i++) {
//                        Uri newUri = Uri.parse(pathList.get(i));
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            newUri = FileProvider.getUriForFile(this, "com.base.provider", new File(newUri.getPath()));
//                        }
//                        ContentResolver cr = this.getContentResolver();
//                        Bitmap bmp = null;
//                        try {
//                            bmp = MediaStore.Images.Media.getBitmap(cr, newUri);
//                        } catch (IOException e) {
//
//                        }
//                        if (bmp != null) {
//                            mAdapter.addData(bmp);
//                            mImgs.add(ToolUtils.ratio(bmp, 240f, 120f));
//                        }
//                    }
                }
                break;
            case SELECT_CAMERA:
                if (resultCode == RESULT_OK) {
//                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
//                    cropPhoto(Uri.fromFile(temp));
                    cropImageUri = Uri.fromFile(fileCropUri);
//                    cropImageUri(imageUri, cropImageUri);
                    ContentResolver cr = this.getContentResolver();
                    Bitmap bmp = null;
                    try {
                        bmp = MediaStore.Images.Media.getBitmap(cr, imageUri);
                    } catch (IOException e) {

                    }
                    if (bmp != null) {
                        mAdapter.addData(bmp);
                        mImgs.add(ToolUtils.ratio(bmp, 240f, 120f));
                    }
                }
                break;
//            case CROP_PHOTO:
//                try {
//                    Bitmap head = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), cropImageUri);
//                    if (head != null) {
//                        mAdapter.addData(head);
//                        mImgs.add(head);
////                        uploadHead(ToolUtils.bitmaptoString(
////                                ToolUtils.compressImage(head)));
//                    }
//                } catch (IOException e) {
//
//                }
        }
    }


    private ArrayList<AlbumFile> mAlbumFiles = new ArrayList<>();
    /**
     * 选择调用多选相册
     */
    public void showMoreImgTypeDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        final android.app.AlertDialog dialog = builder.create();
        View view = View.inflate(this, com.base.R.layout.dialog_select_photo, null);
        TextView tv_select_gallery = (TextView) view.findViewById(com.base.R.id.dialog_select_gallery);
        TextView tv_select_camera = (TextView) view.findViewById(com.base.R.id.dialog_select_camera);
        tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
                if (mImgs.size() < 5) {
                    Album.image(mContext) // Image selection.
                            .multipleChoice()
                            .requestCode(SELECT_GALLERY)
                            .camera(false)
                            .columnCount(3)
                            .selectCount(5 - mImgs.size())
                            .checkedList(mAlbumFiles)
                            .onResult(new Action<ArrayList<AlbumFile>>() {
                                @Override
                                public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                    if (result != null) {
                                        for (int i = 0; i < result.size(); i++) {
                                            Uri newUri = Uri.parse(result.get(i).getPath());
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                                newUri = FileProvider.getUriForFile(mContext, "com.base.provider",
                                                        new File(newUri.getPath()));
                                            }
                                            ContentResolver cr = mContext.getContentResolver();
                                            Bitmap bmp = null;
                                            try {
                                                bmp = MediaStore.Images.Media.getBitmap(cr, newUri);
                                            } catch (IOException e) {

                                            }
                                            if (bmp != null) {
                                                mAdapter.addData(bmp);
                                                mImgs.add(ToolUtils.ratio(bmp, 240f, 120f));
                                            }
                                        }
                                    }
                                }
                            })
                            .onCancel(new Action<String>() {
                                @Override
                                public void onAction(int requestCode, @NonNull String result) {
                                }
                            })
                            .start();
                    dialog.dismiss();
                }
            }
        });
        tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机
            @Override
            public void onClick(View v) {
                autoObtainCameraPermission();
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }
}